<template>
  <div class="vue-echarts">
    <div class="chart-root" v-show="!empty" ref="chartRoot"></div>
    <div class="empty-tips" v-if="empty">暂无数据</div>
  </div>
</template>

<script>
import Echarts from '@libs/echarts'
import { COLORS } from '@controller/echarts'
import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'
export default {
  name: 'VueEcharts',
  components: {},
  props: {
    options: {
      type: Object,
    },
    events: {
      type: Object,
    },
    resizeFlag: {
      type: [String, Number],
    },
    empty: {
      type: Boolean,
    },
  },
  data() {
    return {
      chartInstance: null,
    }
  },
  computed: {},
  watch: {
    options: {
      deep: true,
      handler() {
        this.setOptions()
      },
    },
    resizeFlag() {
      this.resize()
    },
  },
  created() {},
  mounted() {
    this.initChart()
    // window.addEventListener('resize', this.resize)
    addResizeListener(this.$el, this.resize)
  },
  methods: {
    initChart() {
      this.chartInstance = Echarts.init(this.$refs.chartRoot)
      this.setOptions()
      if (this.events) {
        for (const key in this.events) {
          const eventDefine = this.events[key]
          this.chartInstance.on(key, eventDefine.query, eventDefine.fn)
        }
      }
      this.$emit('inited', this.chartInstance)
    },
    setOptions() {
      if (this.options) {
        // 替换默认全局颜色
        const options = { color: COLORS, ...this.options }
        this.$nextTick(() => {
          this.chartInstance.setOption(options)
          this.resize()
        })
      }
    },
    resize(duration = 300) {
      this.chartInstance.resize({
        animation: { duration: duration },
      })
    },
    dispatchAction(type, name) {
      this.chartInstance.dispatchAction({
        type: type,
        name: name,
      })
    },
  },
  beforeDestroy() {
    // window.removeEventListener('resize', this.resize)
    removeResizeListener(this.$el, this.resize)
    this.chartInstance.dispose()
  },
}
</script>
<style lang="scss" scoped>
.vue-echarts {
  width: 100%;
  height: 100%;
  position: relative;
  .chart-root {
    height: 100%;
  }
  .empty-tips {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #666;
    background: #fff;
  }
}
</style>
